package com.totcy.atom.net.interceptor;

import android.content.Context;
import android.text.TextUtils;

import com.totcy.atom.BuildConfig;
import com.totcy.atom.CommonValues;
import com.totcy.atom.net.exception.ApiException;
import com.totcy.atom.utils.UserUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * description: 自定义拦截器，添加请求headers和body处理
 * author: Totcy
 * date: 2017/9/19 17:43
 * update: 2017/9/19
 */

public class CustomInterceptor implements Interceptor {

    private Context context;

    public CustomInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        /*处理header*/
        Request.Builder builder = originalRequest.newBuilder()
                .header("platform", CommonValues.PLATFORM)
                .header("appKey", CommonValues.APP_KEY)
                .header("version", String.valueOf(BuildConfig.VERSION_CODE))
                .header("channel", BuildConfig.FLAVOR);
        String token = UserUtil.getInstances().getUserToken();
        if (!TextUtils.isEmpty(token)) {
            builder.header("Authorization", UserUtil.getInstances().getUserToken());
        }

        Request myRequest = builder.build();
        Response response;
        response = chain.proceed(myRequest);

        if (response.code() == 400) {//返回为token失效
            throw new ApiException(401,"身份验证失效，请重新登录!");
        }

        return response;

    }
}
